//===============================================================================
// Microsoft patterns & practices
// Web Client Software Factory
//===============================================================================
// Copyright � Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using System.Collections.Generic;

using Microsoft.Practices.ObjectBuilder;

using MVPComposibility.ContactManager.DomainModel;

using MVPComposibility.ContactManager.Views.ContactList;
using UserControl = Microsoft.Practices.CompositeWeb.Web.UI.UserControl;

namespace WebApplication.ContactManager
{
	public partial class ContactList : UserControl, IContactListView
	{
		private ContactListPresenter _presenter;

		public event EventHandler Changed;

		private void FireChanged()
		{
			if (Changed != null)
			{
				Changed(this, EventArgs.Empty);
			}
		}

		public void lblTime_Load(object sender, EventArgs e)
		{
			lblTime.Text = DateTime.Now.ToString();
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				_presenter.OnViewInitialized();
			}
			_presenter.OnViewLoaded();
		}

		[CreateNew]
		public ContactListPresenter Presenter
		{
			get
			{
				return _presenter;
			}
			set
			{
				_presenter = value;
				_presenter.View = this;
			}
		}

		public event EventHandler SelectedContactIndexChanged;

		public int SelectedContactIndex
		{
			get { return ContactsGrid.SelectedIndex; }
			set
			{
				ContactsGrid.SelectedIndex = value;
				SelectedIndexLabel.Text = SelectedContactIndex.ToString();
				FireChanged();
			}
		}

		public void SetContactList(IEnumerable<Contact> contacts)
		{
			ContactsGrid.DataSource = contacts;
			ContactsGrid.DataBind();
			FireChanged();
		}

		protected void OnContactsGridSelectedIndexChanged(object sender, EventArgs e)
		{
			OnSelectedContactIndexChanged(this, EventArgs.Empty);
			SelectedIndexLabel.Text = SelectedContactIndex.ToString();
		}

		protected virtual void OnSelectedContactIndexChanged(object sender, EventArgs e)
		{
			if (SelectedContactIndexChanged != null)
			{
				SelectedContactIndexChanged(sender, e);
			}
		}
	}
}